import copy
from core.tools.custom_requests import CustomRequests
from finance_c2c.local_settings import ONLINE, CoffeeClientPsw, CoffeeClientUrl, CoffeeClientUser
from core.tools.encryption import hashlib_md5


class CoffeeApi(CustomRequests):
    def __init__(self, orderNo, VMC, pid, PTYPE="MEMBERPAY"):
        """
        :param orderNo: 咖啡机订单号
        :param VMC: 机器号
        :param pid: 产品id
        :param czb_payCode:
        """
        self.ID = orderNo
        self.VMC = VMC
        self.PTYPE = PTYPE
        self.PID = pid
        self.user = CoffeeClientUser
        self.password = CoffeeClientPsw
        self.FASTCODE = 999  # 会员支付方式
        self.data = {"ID": self.ID, "USERNAME": self.user, "password": self.password, "VMC": self.VMC,
                     "PTYPE": self.PTYPE,
                     "PID": self.PID, "FASTCODE": self.FASTCODE}
        self.base_url = CoffeeClientUrl

    def get_mac(self):
        message = "ID={ID}&USERNAME={USERNAME}&PASSWORD={password}&VMC={VMC}&PTYPE={PTYPE}&PID={PID}&FASTCODE={FASTCODE}".format(
            **self.data)
        return hashlib_md5(message)

    def verify(self, base_value):
        data = {"ID": self.ID, "PID": self.PID, "VMC": self.VMC, "USER": self.user}
        print(data, "verify  data")
        param = "ID={ID}&PID={PID}&VMC={VMC}&USER={USER}".format(**data)
        print(param, "param")
        value = hashlib_md5(param)
        print(value, "value", "base_value")
        return value == base_value

    def member_pay(self):
        data = copy.deepcopy(self.data)
        data.pop("password")
        data["MAC"] = self.get_mac()
        if ONLINE:
            url = "FASTCODE"
        else:
            url = "FASTCODE"
        param = "?ID={ID}&PTYPE={PTYPE}&PID={PID}&VMC={VMC}&FASTCODE={FASTCODE}&USERNAME={USERNAME}&MAC={MAC}".format(
            **data)
        # raise Exception("需要白天去现场测试")
        print(param, "会员付请求参数")
        try:
            response = self.get(url=url + param)
            print(response, "会员支付，通知制作咖啡")
            return response
        except Exception as e:
            print(e, "会员付错误")

